"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : CLEAN CONNECTION
Case Name   : CLEAN CONNECTION TO ALL 指定FORCE，删除正在使用的连接成功
Create At   : 2022-05-10
@zou_jialiang0501125467
Description :
    1、创建数据库
    2、创建用户
    3、线程1连接数据库
    4、线程2执行清理操作
    5、清理环境
Expect      :
    1、创建数据库，expect: 成功
    2、创建用户，expect: 成功
    3、线程1连接数据库，expect: 成功
    4、线程2执行清理操作，expect: 成功
    5、清理环境，expect: 成功
History     :
"""

import os
import unittest
import time
from yat.test import Node
from yat.test import macro

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CleanConnection(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_root = Node('PrimaryRoot')
        self.constant = Constant()
        self.db_name = 'd_clean_0005'
        self.u_name = 'u_clean_0005'
        self.flag = 'CLEAN CONNECTION'

    def test_main(self):
        step_txt = '----step1: 创建数据库，expect: 成功----'
        self.log.info(step_txt)
        create_sql = f'drop database if exists {self.db_name};' \
            f'create database {self.db_name};'
        create_result = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(create_result)
        self.assertTrue(
            create_result.count(self.constant.CREATE_DATABASE_SUCCESS) == 1,
            '执行失败:' + step_txt)

        step_txt = '----step2: 创建用户，expect: 创建成功----'
        self.log.info(step_txt)
        create_sql = f"drop user if exists {self.u_name} cascade;" \
            f"create user {self.u_name} with " \
            f"password '{macro.COMMON_PASSWD}';"
        create_result = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(create_result)
        self.assertTrue(
            create_result.count(self.constant.CREATE_ROLE_SUCCESS_MSG) == 1,
            '执行失败:' + step_txt)

        step3_txt = '----step3: 线程1连接数据库;expect:成功----'
        self.log.info(step3_txt)
        sql_cmd1 = 'select sysdate;select pg_sleep(60);select sysdate;'
        excute_cmd1 = f'-U {self.u_name} -W "{macro.COMMON_PASSWD}" '
        db_name = self.db_name
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql_cmd1, excute_cmd1, db_name,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(3)

        step4_txt = '----step4: 线程2执行清理操作，expect: 清理失败----'
        self.log.info(step4_txt)
        sql_cmd2 = f'''clean connection to all force 
                            for database {self.db_name};
                '''
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(sql_cmd2,))
        session2.setDaemon(True)
        session2.start()

        self.log.info("----session1执行结果----")
        session1.join()
        session1_result = session1.get_result()
        self.log.info(session1_result)
        self.assertIn('connection to server was lost', session1_result,
                      '执行失败:' + step3_txt)

        self.log.info("----session2执行结果----")
        session2.join()
        session2_result = session2.get_result()
        self.log.info(session2_result)
        self.assertIn(self.flag, session2_result,
                      '执行失败:' + step4_txt)

    def tearDown(self):
        self.log.info('----this is teardown----')
        step_txt = '----step5: 删除数据库和用户----'
        self.log.info(step_txt)
        drop_sql = f'drop database if exists {self.db_name};' \
                   f'drop user if exists {self.u_name} cascade;'
        drop_result = self.pri_sh.execut_db_sql(drop_sql)
        self.log.info(drop_result)

        self.log.info(f'-----{os.path.basename(__file__)} end-----')
